#/usr/bin/python

from util import Util
from util import InterfaceTable
from gen_java import JavaParser
from gen_java import *
import re
import sys


class DaoTable:
    def __init__(self,domain):
        self.dao_table=[]
        self.domain=domain
    def add_interface_to_table(self,interfaceTable):
        if "InterfaceTable" not in interfaceTable.__class__.__name__:
            print("must add the interface class")
            sys.exit()
        self.dao_table.append(interfaceTable)
    def gen_java_dao(self):
        gen_dao="package com.trendata.dao;\n"
        gen_dao=gen_dao+"class I"+self.domain+"Dao{\n";
        for interface in self.dao_table:
            gen_dao=gen_dao+interface.gen_interface()+"\n"
        gen_dao=gen_dao+"}\n"
        return gen_dao
            
class DaoParser:
    def __init__(self):
        pass
    def parser(self,domain,sentences):
        self.domain=domain
        util=Util()
        sentence=sentences.split("|")
        for single_sentence in sentence:
            yield self.parser_single_dao(single_sentence)
    def parser_single_dao(self,sentences):
        single_inter=InterfaceTable()
        sentences=re.sub("^\s+","",sentences)
        for sentence in sentences.split(","):
            typeid=sentence.split(":")[0]
            if typeid == 'id':
                single_inter.set_id(sentence.split(":")[1])
            elif typeid == 'parameter':
                ids=re.split("[ ]",sentence.split(":")[1])
                single_inter.add_parameter(ids[0],ids[1])
            elif typeid == 'return':
                returntype=sentence.split(":")[1]
                returntype=re.sub("\s","",returntype)
                single_inter.set_return(returntype)
        #pdb.set_trace()
        if not hasattr(single_inter,"id") or single_inter.parameter.__len__ == 0 or not hasattr(single_inter,"returntype"):
            print("sentence can't parser in to method"+sentences)
            sys.exit()
        return single_inter

    def run_parser(self,domain,sentence):
        gen_dao=self.get_dao_table(domain,sentence)
        return gen_dao.gen_java_dao()

    def get_dao_table(self,domain,sentence):
        gen_dao=DaoTable(domain)
        for item in self.parser(domain,sentence):
            gen_dao.add_interface_to_table(item)
        return gen_dao
            


class MapTable:
    def __init__(self,javamap,daomap):
        if 'JavaTable' not in javamap.__class__.__name__:
            print("MapTable must init with javatable")
            sys.exit()
        if 'DaoTable' not in daomap.__class__.__name__:
            print("DaoMap must be with daomap")
            sys.exit()
        self.javamap=javamap
        self.daomap=daomap

    def gen_map(self):
        return self.__gen_dao_interface__()

    def __gen_dao_map__(self):
        javadao="I"+self.javamap.domain+"Dao"
        return "<mapper namespace=\""+self.javamap.package+"."+javadao+"\">"
    def __gen_item_map__(self):
        util=Util()
        gen_item="<resultMap id=\""+ util.domain_to_ResultMap(self.javamap.domain)+"\" type=\""+self.javamap.domain+"\">"
        for item in self.javamap.table[0]:
            if item=='id':
                gen_item="<id column=id property=\"id\"/> \n"
            else:
                gen_item=gen_item+"<result column=\""+util.javaid_to_sqlid(item)+"\" property=\""+item+"\" /> \n"
        gen_item=gen_item+"</resultMap>"

    def __gen_dao_interface__(self):
        map_str=""
        daomap_Table=[]
        for interface in self.daomap.dao_table:
            daomap_Table.append(self.__getstr_by_daotype__(interface))
            map_str=map_str+self.__getstr_by_daotype__(interface)
        return map_str
        
    def __getstr_by_daotype__(self,interface):
        if "insert" in interface.id or "add" in interface.id: 
            daotype="insert"
            return self.__gen_sql_insert__(interface)
        elif "update" in interface.id:
            daotype="update"
            return self.__gen_sql_update__(interface)
        elif "delete" in interface.id:
            daotype="delete"
            return self.__gen_sql_delete__(interface)
        elif "select" in interface.id:
            return self.__gen_sql_select__(interface)
        else:
            daotype="void"
            print("interface unkown"+interface.id)

    def __gen_sql_insert__(self,interface):
        util=Util()
        gen_insert=""
        if interface.parameter.__len__()==0:
            print("you must write the interface")
        elif "List" in interface.parameter[0][0]:
            gen_select="<update id=\""+interface.id+"\"parameterType=\""+interface.parameter[0][0]+"\">\n"
            gen_select=gen_select+"\t\t<![CDATA[ insert into "+util.javaid_to_sqlid(self.javamap.domain)+"//TODO \n"
            gen_select=gen_select+"]]>"
        elif self.javamap.domain in interface.parameter[0][0]:
            gen_insert="<insert id=\""+interface.id+"\"parameterType=\""+util.domain_to_ResultMap(self.javamap.domain)+"\">\n"
            gen_insert=gen_insert+"\t\t<![CDATA[ insert into "+util.javaid_to_sqlid(self.javamap.domain)+"\n"
            sql_sentence=None
            value_sentence=None
            update_sentence=None
            import pdb
            for column in self.javamap.table:
                javaid=column[0]
                javatype=column[1]
                sqlid=util.javaid_to_sqlid(javaid)
                if sql_sentence is None:
                    sql_sentence="("+sqlid
                    value_sentence="(#"+javaid+"}"
                    update_sentence="\t\ton duplicate key update\n\t\t"+sqlid+"values("+javaid+")"
                else:
                    sql_sentence=sql_sentence+","+util.javaid_to_sqlid(javaid)
                    value_sentence=value_sentence+",#{"+javaid+"}"
                    update_sentence=update_sentence+",\n\t\t\t"+sqlid+"=values("+javaid+")"
            sql_sentence="\t\t\t"+sql_sentence+")"
            value_sentence=value_sentence+")\n"
            gen_insert=gen_insert+sql_sentence+" values "+value_sentence +"\t\t\t"+update_sentence
            gen_insert=gen_insert+"\n]]> <insert>\n"
        return gen_insert

            
    def __gen_sql_select__(self,interface):
        util=Util()
        gen_select="<update id=\""+interface.id+"\" parameterType=\""+interface.parameter[0][0]+"\">\n"
        gen_select=gen_select+"<![CDATA[ select * from "+util.javaid_to_sqlid(self.javamap.domain)+"//TODO \n"
        gen_select=gen_select+"]]>\n"
        return gen_select
    
    def __gen_sql_delete__(self,interface):
        util=Util()
        gen_delete="<delete id=\""+interface.id+"\" parameterType=\""+util.domain_to_ResultMap(self.javamap.domain)+"\">\n"
        gen_delete=gen_delete+"<![CDATA[ delete from "+util.javaid_to_sqlid(self.javamap.domain)+"//TODO \n"
        gen_delete=gen_delete+"]]>\n"
        return gen_delete

    def __gen_sql_update__(self,interface):
        util=Util()
        gen_update="<update id=\""+interface.id+"\" parameterType=\""+util.domain_to_ResultMap(self.javamap.domain)+"\">\n"
        gen_update=gen_update+"<![CDATA[ update from "+util.javaid_to_sqlid(self.javamap.domain)+"//TODO \n"
        gen_update=gen_update+"]]>\n"
                
            

if __name__=="__main__":
    parse_dao_file=" id:insertSelectItem,parameter:SelectItem select,return: int"
    parse_java_file="ItemId Long|pictureUrl String,varchar(20)|setTime Timestamp|Sid Long"
    daoparser=DaoParser()
    daotable=daoparser.get_dao_table("selectItem",parse_dao_file)
    print(daoparser.run_parser("selectItem",parse_dao_file))
    javaparser=JavaParser()
    javamap=javaparser.get_java_table("com.trendata","SelectItem",parse_java_file)
    daoparser=DaoParser()
    daomap=daoparser.get_dao_table("selectItem",parse_dao_file)
    tablemap=MapTable(javamap,daomap)
    print(tablemap.gen_map())

    
    
    
